package com.csaba.db.actions;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

import com.csaba.db.DatabaseManager;
import com.csaba.util.LoggerHelper;

/**
 * Our sample action implements workbench action delegate.
 * The action proxy will be created by the workbench and
 * shown in the UI. When the user tries to use the action,
 * this delegate will be created and execution will be 
 * delegated to it.
 * @see IWorkbenchWindowActionDelegate
 */
public class CloseUserAction implements IWorkbenchWindowActionDelegate
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	private IWorkbenchWindow window;

	/**
	 * The constructor.
	 */
	public CloseUserAction()
	{
	}

	/**
	 * The action has been activated. The argument of the
	 * method represents the 'real' action sitting
	 * in the workbench UI.
	 * @see IWorkbenchWindowActionDelegate#run
	 */
	public void run( final IAction action )
	{
		final DatabaseManager dbm = DatabaseManager.getInstance();

		if ( !dbm.hasActiveDatabase() )
		{
			MessageDialog.openInformation(window.getShell(), "Close Database", "There is no active database open now.");
		}
		else
		{
			try
			{
				dbm.closeActiveDatabase(null);
			}
			catch ( final CoreException ex )
			{
				MessageDialog.openError(window.getShell(), "Error", "Exception occured: " + ex.getMessage());
				logger.log(Level.SEVERE, "Error closing open database.", ex);
			}
		}
	}

	/**
	 * Selection in the workbench has been changed. We 
	 * can change the state of the 'real' action here
	 * if we want, but this can only happen after 
	 * the delegate has been created.
	 * @see IWorkbenchWindowActionDelegate#selectionChanged
	 */
	public void selectionChanged( final IAction action, final ISelection selection )
	{
	}

	/**
	 * We can use this method to dispose of any system
	 * resources we previously allocated.
	 * @see IWorkbenchWindowActionDelegate#dispose
	 */
	public void dispose()
	{
	}

	/**
	 * We will cache window object in order to
	 * be able to provide parent shell for the message dialog.
	 * @see IWorkbenchWindowActionDelegate#init
	 */
	public void init( final IWorkbenchWindow window )
	{
		this.window = window;
	}
}